/*
 * @Author: 郭桓
 * @Date: 2019-02-20 11:27:16
 * @LastEditors: GuoHuan
 * @LastEditTime: 2019-03-08 15:27:43
 * @Description: file content
 */
// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const Utils = require('Utils');
const KHItem = require('KHItem');
cc.Class({
    extends: cc.Component,

    properties: {
        iconMission: {
            default: [],
            type: cc.Toggle
        },
        sprdList: {
            default: [],
            type: cc.Integer
        },
        bgList: {
            default: [],
            type: cc.SpriteFrame
        },
        iconList: {
            default: [],
            type: cc.SpriteFrame
        },
        dropList: {
            default: [],
            type: cc.SpriteFrame
        },
        winInfoList: {
            default: [],
            type: cc.SpriteFrame
        },
        resultNode: cc.Node,
        spriteLP: cc.Prefab, //罗盘
        spriteKh: cc.Prefab,
        btnBack: cc.Node, //退出
        btnTest: cc.Node,
        btnRank: cc.Node, //排行榜
        winRank: cc.Node, //
        imgRule: cc.Node,
        btnGameStart: cc.Node, //游戏开始的按钮
        goldNode: cc.Node, //右上的金币区
        iconLpalate: cc.Node, //中间的转盘
        gameLayer: cc.Node,
        imgBg: cc.Sprite, //背景图片
        imgKH: cc.Node, //口红
        nodeKH: cc.Node, //口红note
        clockNode: cc.Node, //时钟
        _gameLpalate: cc.Node,
        _payCost: 0, //当前关卡的消耗
        _listen: 0, //第几小关
        _startY: 0,
        _isGame: false,
        _roateSpd: 0,
        _randomTime: null, //随机出来的时间
        _utils: null,
        _moveSpd: 0,
        _timeClock: 0, //当前的时间
        _life: 0,
        _timeFlag: 0,
        _lineY: 0, //用于判断是否插入成功的Y值
        _touchKH: null
    },

    // LIFE-CYCLE CALLBACKS:    

    onLoad() {
        this._isGame = false;
        this.node.getChildByName('win_info3').active = false;
        this.node.getChildByName('win_info4').active = false;
        this.resultNode.active = false;
        this.clockNode.active = false;
        this.resultNode.zIndex = 100;
        this.nodeKH.active = false;
        this._timeClock = 30;
        this._listen = 0;
        this._startY = this.imgKH.y;
        this._utils = Utils.singleton;
        if (Utils.singleton == null) {
            Utils.singleton = new Utils.Utils();
            this._utils = Utils.singleton;
        }

        this._moveSpd = 1500;
        this._startY -= 150;

        this.iconLpalate.zIndex = 10;
        this.gameLayer.zIndex = 5;
        this.imgRule.zIndex = 15;
        this._lineY = this.iconLpalate.y;
        this._gameLpalate = null;
        this.winRank.zIndex = 100;
        this.node.getChildByName('win_info4').zIndex = 50;
    },

    start() {
        this._listen = 0;
        this.winRank.active = false;
        this.gameLayer.removeAllChildren();
        this.resultNode.active = false;
        this.randomBg();
        //刚开始的时候  
        this.node.on(cc.Node.EventType.TOUCH_END, this.touch.bind(this), this);
        cc.director.getCollisionManager().enabled = true;
        this._payCost = this._utils.getPay();

        this.btnRank.active = true;
        this.btnGameStart.active = true;
        this.btnTest.active = true;
        this.imgRule.active = true;
        this.btnBack.active = true;
        this.goldNode.active = true;
        this.nodeKH.active = false;
        this.clockNode.active = false;

        if (this._utils.userinfo.gold)
            this.goldNode.getChildByName('gold').getComponent(cc.Label).string = this._utils.userinfo.gold;

        this.node.getChildByName('missionGroup').getChildByName('mission3').active = true;
        if (this._payCost == 0) {
            this.node.getChildByName('missionGroup').getChildByName('mission3').active = false;
            this.btnGameStart.active = false;
        } else {
            this.btnTest.active = false;
            this.btnGameStart.getChildByName('gold').getComponent(cc.Label).string = this._payCost;
        }
    },

    updateGold() {
        this.goldNode.getChildByName('gold').getComponent(cc.Label).string = this._utils.userinfo.gold;
    },


    /**
     * @description: 延时回调
     * @param {type} 
     * @return: 
     */
    delaytoShow() {
        this.gameOver(false);
    },

    delaytoShowWin() {
        this.gameOver(true);
    },
    /**
     * @description:   碰撞回调
     * @param {type} 
     * @return: 
     */
    fail() {
        this._isGame = false;
        this.gameLayer.stopAllActions();
        // this.iconLpalate.stopAllActions();
        if (this._touchKH) {
            this._touchKH.stopAllActions();
        }
        this.unschedule(this.updatetime);
        this.unschedule(this.updateColck);
        this.gameLayer.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(this.delaytoShow.bind(this), this)));
    },

    /**
     * @description:   游戏结束了
     * @param {type} 
     * @return: 
     */
    gameOver(result) {
        this._isGame = false;
        if (this._touchKH != null) {
            this._touchKH.isMove = false;
            this._touchKH.stopAllActions();
        }
        this.gameLayer.stopAllActions();

        this.unschedule(this.updatetime);
        this.unschedule(this.updateColck);
        if (result) {
            //为true了
            if (this._payCost == 0 && this._listen == 1) {
                //测试模式。显示
                this.node.getChildByName('win_info3').active = true;
                return;
            }
            if (this._listen == 2) {
                //完全赢了
                // this.resultNode.active = true;
                this.gameLayer.removeAllChildren();
                this.node.getChildByName('win_info4').active = true;
            } else {
                //播放动画
                this._listen++;
                this._utils.loadAnim(this._listen + 1, 200);
                this.gameLayer.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(function() {
                    this.gameLayer.removeAllChildren();
                    this.gameLayer.stopAllActions();
                    this._utils.gameStartAnim();
                    this.gameStart(this._listen);
                }.bind(this), this)));
            }
            this.randomBg();
        } else {
            this.resultNode.active = true;
            if (this._utils.randomNums(0, 1) == 1) {
                this.resultNode.getChildByName('img_result1').active = true;
                this.resultNode.getChildByName('img_result2').active = false;
            } else {
                this.resultNode.getChildByName('img_result1').active = false;
                this.resultNode.getChildByName('img_result2').active = true;
            }
        }
    },


    playAnim(body) {
        var action = cc.sequence(cc.moveBy(0.1, cc.v2(0, 15)), cc.moveBy(0, cc.v2(0, -20)), cc.moveBy(0, cc.v2(0, 5)));
        this.gameLayer.runAction(action);
    },

    update(dt) {
        if (this._isGame) {
            if (this._touchKH && this._touchKH.isMove) {
                if (this._touchKH.y >= this._lineY) {
                    this._touchKH.stopAllActions();
                    this._touchKH.removeFromParent(false);
                    let rotation = this.gameLayer.getRotation();
                    rotation = rotation % 360;
                    this.gameLayer.addChild(this._touchKH);
                    this._touchKH.removeComponent(KHItem);
                    this._touchKH.rotation = -rotation;
                    this._touchKH.isMove = null;
                    this._touchKH.x = 0;
                    this._touchKH.y = 0;
                    if (this._listen == 2 && this._life < 5) {
                        if (this.list < 3) {
                            this._roateSpd = this.sprdList[2];
                        } else {
                            if (this._roateSpd > 0) {
                                this._roateSpd += (this.sprdList[2] - this.sprdList[1]) / 10;
                            } else {
                                this._roateSpd -= (this.sprdList[2] - this.sprdList[1]) / 10;
                            }
                        }
                        this.gameLayer.stopAllActions();
                        this.gameLayer.runAction(cc.repeatForever(cc.rotateBy(1, this._roateSpd)));
                    }
                    this.playAnim(this._touchKH);
                    this.createKH();
                    if (this._touchKH == null) {
                        this.playLPDeadAnim();
                    }
                }
            }
        }
    },

    /**
     * 播放罗盘死掉的动画
     */
    playLPDeadAnim() {
        this.unschedule(this.updatetime);
        this.unschedule(this.updateColck);
        if (this._touchKH != null) {
            this._touchKH.stopAllActions();
        }
        this.gameLayer.stopAllActions();
        // this._gameLpalate.removeFromParent(false);
        // this.node.addChild(this._gameLpalate);
        // this._gameLpalate.y = this.iconLpalate.y;
        // this._gameLpalate.setRotation(this.gameLayer.getRotation() % 360);
        let rotation = this.gameLayer.getRotation() % 360;

        this.gameLayer.setRotation(0);

        for (let i = 0; i < this.gameLayer.childrenCount; i++) {
            let item = this.gameLayer.children[i];
            if (item == this._gameLpalate)
                continue;
            // item.setRotation(0);
            // item.getChildByName('spr').setRotation(item.getRotation() + rotation);
            item.setRotation(item.getRotation() + rotation);
        }




        let node1 = this._gameLpalate.getChildByName('mask1');
        let node2 = this._gameLpalate.getChildByName('mask2');
        let node3 = this._gameLpalate.getChildByName('mask3');
        // node1.setRotation(rotation);
        // node2.setRotation(rotation);
        // node3.setRotation(rotation);

        node1.getChildByName('spire').setRotation(rotation);
        node2.getChildByName('spire').setRotation(rotation);
        node3.getChildByName('spire').setRotation(rotation);

        // return;

        //开始播放动画



        node1.runAction(cc.sequence(cc.moveBy(0.1, cc.v2(-10, 50)), cc.moveBy(0.2, cc.v2(-20, -80)), cc.spawn(cc.fadeTo(2, 0), cc.moveBy(2, cc.v2(-200, -1200)))));
        node2.runAction(cc.sequence(cc.moveBy(0.1, cc.v2(-30, 30)), cc.moveBy(0.2, cc.v2(-30, -50)), cc.spawn(cc.fadeTo(2, 0), cc.moveBy(2, cc.v2(-100, -1000)))));
        node3.runAction(cc.sequence(cc.moveBy(0.1, cc.v2(10, 20)), cc.moveBy(0.2, cc.v2(20, -40)), cc.spawn(cc.fadeTo(2, 0), cc.moveBy(2, cc.v2(100, -900)))));



        for (let i = 0; i < this.gameLayer.childrenCount; i++) {
            let item = this.gameLayer.children[i];
            if (item == this._gameLpalate)
                continue;

            item.getChildByName('spr').runAction(cc.rotateTo(1, -item.getRotation()));
            item.runAction(cc.repeatForever(cc.moveBy(0.1, cc.v2(0, -100))));
        }


        this.gameLayer.stopAllActions();
        this.gameLayer.runAction(cc.sequence(cc.delayTime(2), cc.callFunc(this.delaytoShowWin.bind(this), this)));


        if (this.winInfoList.length > this._listen) {
            if (this._payCost == 0 && this._listen == 1) {
                return;
            }
            let winInfo = new cc.Node();
            winInfo.addComponent(cc.Sprite);
            let spr = winInfo.getComponent(cc.Sprite);
            spr.spriteFrame = this.winInfoList[this._listen];
            this.gameLayer.addChild(winInfo);
            winInfo.opacity = 0;
            winInfo.runAction(cc.fadeTo(1, 255));
            winInfo.zIndex = 100;
        }
    },

    /**
     * @description: 刷新时间
     * @param {type} 
     * @return: 
     */
    updateColck(dt) {
        this._timeClock--;
        if (this._timeClock <= 0) {
            this._timeClock = 0;
            this.unschedule(this.updateColck);
            this.gameOver(false);
        }
        this.clockNode.getChildByName("time").getComponent(cc.Label).string = this._timeClock;
    },


    /**
     * @description: 刷新随机转向
     * @param {type} 
     * @return: 
     */
    updatetime(dt) {
        if (this._isGame && this._randomTime > 0) {
            this._timeFlag++;
            if (this._timeFlag >= this._randomTime * 10) {
                this.gameLayer.stopAllActions();
                this._roateSpd = -this._roateSpd;
                this.gameLayer.runAction(cc.repeatForever(cc.rotateBy(1, this._roateSpd)));
                this.getRandomTime();
            }
        }
    },

    onCollisionEnter(other, self) { //碰撞则播放爆炸动画
        // cc.log(" here!!");
        if (other.node.group != 'bullet') {
            cc.log("bullet");
            return;
        }
        if (other.node.group == 'bullet') //检测碰撞组
        {
            other.node.removeFromParent();
            this.hp -= 1;
            if (this.hp == 0) {
                //  enemyReq.add_Score();
                this.node.group = 'default'; //防止播放爆炸动画时继续检测导致神奇的事情发生
                var en = this.node.getComponent(cc.Animation);
                var na = this.node.name;
                en.play(na + "_des"); //播放动画
                en.on('finished', function(e) {
                    this.node.removeFromParent();
                }, this);
            }
        }
    },

    getRandomTime() {
        this._timeFlag = 0;
        if (this._listen == 0) {
            this._randomTime = 0;
        } else if (this._listen == 1) {
            this._randomTime = this._utils.randomNums(3, 5);
        }else {
            this._randomTime = this._utils.randomNums(1, 2);
        }
    },



    showLife() {
        let hideNums = 13 - this._life;
        for (let i = 0; i < hideNums; i++) {
            this.nodeKH.getChildByName('kh' + (13 - i)).active = false;
        }
    },



    createKH() {
        if (this._life == 0) {
            this._touchKH = null;
            return null;
        }
        this._life--;
        this.showLife();
        this._touchKH = cc.instantiate(this.spriteKh);
        this.node.addChild(this._touchKH);
        this._touchKH.addComponent(KHItem);
        this._touchKH.getComponent(KHItem).setTouchListener(this.fail.bind(this));
        this._touchKH.addc
        this._touchKH.y = this._startY;
        let fixPoint = this._touchKH.getAnchorPoint().y - 0.5
        this._touchKH.y += (fixPoint * this._touchKH.height);
        return this._touchKH;
    },


    showKH() {
        this._isGame = true;
        this.imgKH.active = false;
        this._touchKH.active = true;
    },


    randomBg() {
        let idx = this._utils.randomNums(0, this.iconList.length - 1);
        if (this._listen == 0) {
            idx = 0;
        } else if (this._listen == 1) {
            idx = 1;
        } else if (this._listen == 2) {
            idx = 2;
        }
        this.imgBg.spriteFrame = this.bgList[idx];
        this.iconLpalate.active = true;

        this.iconLpalate.getComponent(cc.Sprite).spriteFrame = this.iconList[idx];
        this.iconLpalate.setName(idx + '');
    },


    /**
     * @description: 游戏开始
     * @param {type} 
     * @return: 
     */
    gameStart(listen) {

        this.node.getChildByName('win_info4').active = false;
        this.node.getChildByName('win_info3').active = false;
        this._isGame = false;
        this.imgRule.active = false;
        this.btnTest.active = false;
        this.resultNode.active = false;
        this.btnBack.active = false;
        this.goldNode.active = false;
        this.btnGameStart.active = false;
        this.btnRank.active = false;
        this.nodeKH.active = true;
        this._timeClock = 30;
        this.clockNode.active = true;
        this.clockNode.getChildByName('time').getComponent(cc.Label).string = this._timeClock;
        this.unschedule(this.updatetime);
        this.unschedule(this.updateColck);
        if (this._touchKH) {
            this._touchKH.removeFromParent();
            this._touchKH = null;
        }


        // return;
        // //======    结束            =======

        this._listen = listen;
        this.iconMission[this._listen].check();
        let nums = 6;
        if (this._listen == 1) {
            nums = 10;
        } else if (this._listen == 2) {
            nums = 13;
            this._timeClock = 60;
        }

        this._life = nums;

        for (let i = 0; i < 13; i++) {
            this.nodeKH.getChildByName('kh' + (i + 1)).active = true;
        }

        this.createKH();
        this._touchKH.active = false;
        this.imgKH.active = true;
        if (this._listen == 0) {
            this.imgKH.runAction(cc.sequence(cc.moveTo(0.2, cc.v2(this.imgKH.x, this._startY)), cc.callFunc(this.showKH.bind(this), this)));
        } else {
            this.imgKH.active = false;
            this.imgKH.y = this._startY;
            this.showKH();
        }


        this._roateSpd = this.sprdList[this._listen];
        if (this._listen >= 2) {
            this._roateSpd = this.sprdList[1];
        }

        this.gameLayer.removeAllChildren();
        // this.iconLpalate.runAction(cc.repeatForever(cc.rotateBy(1, this._roateSpd)));

        this.iconLpalate.active = false;
        if (this._gameLpalate != null) {
            this._gameLpalate.removeFromParent();
            this._gameLpalate = null;
        }

        this._gameLpalate = new cc.instantiate(this.spriteLP);
        this.gameLayer.addChild(this._gameLpalate);

        for (let i = 0; i < 3; i++) {
            this._gameLpalate.getChildByName('mask' + (i + 1)).getChildByName('spire').getComponent(cc.Sprite).spriteFrame = this.iconLpalate.getComponent(cc.Sprite).spriteFrame;
        }

        this._gameLpalate.zIndex = 100;



        this.gameLayer.runAction(cc.repeatForever(cc.rotateBy(1, this._roateSpd)));

        this.getRandomTime();
        this.schedule(this.updatetime, 0.1);
        this.schedule(this.updateColck, 1);
    },



    /**
     * @description: 插入KH
     * @param {type} 
     * @return: 
     */
    touch() {
        if (!this._isGame) return;
        if (this._touchKH == null)
            return;
        if (this._touchKH.isMove)
            return;
        this._touchKH.isMove = true;
        this._touchKH.runAction(cc.repeatForever(cc.moveBy(1, cc.v2(0, this._moveSpd))));

        if (this._listen == 2 && this._life <= 5) {
            //需要害人
            if (this._timeFlag >= 10) {
                this._timeFlag = 5;
            }
        }

    },

    onViewClick(sender, data) {
        cc.log(" click data = " + data);
        switch (data) {
            case 'exit':
                {
                    cc.director.loadScene('main');
                }
                break;
            case 'start':
                {
                    if (this._payCost == 0) {
                        this.gameStart(0);
                    } else {
                        if (this._utils.userinfo.gold >= this._payCost) {
                            this._utils.loadAnim(1);
                            this._utils.request("over", "GET", {
                                goodId: this._utils.getID(),
                                account: this._utils.userinfo.account,
                                loginVar: this._utils.userinfo.loginId
                            }, function(err, data) {
                                if (err == null) {
                                    this._utils.gameStartAnim(true);
                                    this.gameStart(0);
                                    //成功了 现在需要扣掉相应的金币
                                    this._utils.userinfo.gold -= this._payCost;
                                    this.updateGold();
                                }
                            }.bind(this), false);
                        } else {
                            this._utils.showShop();
                        }
                    }
                }
                break;
            case 'continue':
                {
                    this.start();
                }
                break;
            case 'buy':
                {
                    this._utils.showShop();
                }
                break;
            case 'test':
                {
                    // this.gameLayer.rotation += 5;
                    // this.iconLpalate.rotation += 5;
                    // if (this._isGame) {
                    //     this._isGame = false;
                    //     this.iconLpalate.stopAllActions();
                    //     this.gameLayer.stopAllActions();
                    //     if (this._touchKH.isMove) {
                    //         this._touchKH.isMove = false;
                    //         this._touchKH.stopAllActions();
                    //     } else {
                    //         this._touchKH.isMove = true;
                    //         this._touchKH.runAction(cc.repeatForever(cc.moveBy(1, cc.v2(0, 300))));
                    //     }
                    // } else {
                    //     this._isGame = true;
                    //     this.iconLpalate.runAction(cc.repeatForever(cc.rotateBy(1, -this._roateSpd)));
                    //     this.gameLayer.runAction(cc.repeatForever(cc.rotateBy(1, -this._roateSpd)));
                    //     if (this._touchKH.isMove) {
                    //         this._touchKH.isMove = false;
                    //         this._touchKH.stopAllActions();
                    //     } else {
                    //         this._touchKH.isMove = true;
                    //         this._touchKH.runAction(cc.repeatForever(cc.moveBy(1, cc.v2(0, 300))));
                    //     }
                    // }
                }
                break;
            case 'log':
                {
                    cc.log("log!!");
                }
                break;
            case 'rank': //排行榜
                {
                    this.winRank.active = true;
                }
                break;
            case 'closewin':
                {
                    this.winRank.active = false;
                }
                break;
            case 'goshop':
                {
                    if (this._utils.userinfo.gold >= 3) {

                    } else {
                        this.node.getChildByName('win_info4').active = false;
                        this.node.getChildByName('win_info3').active = false;
                        this._utils.showShop();
                    }
                    cc.director.loadScene('main');
                }
                break;
            case 'get':
                {

                    cc.director.loadScene('main', function() {
                        let uiJS = cc.director.getScene().getChildByName('Canvas').getComponent('MainActivity');
                        if(uiJS){
                            uiJS.changeKH(this._utils._payGoodsId)
                        }
                    }.bind(this));

                }
                break;
        }
    }

    // update (dt) {},
});